package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Id int
	Gender string
	Name string
}

type Class struct {
	Title string
	Students []Student
}

func main() {
	c := Class{
		Title: "Go语言101",
		Students: make([]Student, 0, 200),
	}

	for i := 1; i <= 10; i++ {
		s := Student{
			Id: i,
			Gender: "男",
			Name: fmt.Sprintf("学生%d", i),
		}
		c.Students = append(c.Students, s)
	}

	fmt.Println(c)

	strByte, err := json.Marshal(c)
	if err!= nil {
		fmt.Println(err)
		return
	} else {
		str := string(strByte)
		fmt.Println(str)
	}

	fmt.Println("~~~~~~~~~~~~~~~~~~~~~")

	// 字符串转结构体
	str1 := `{"Title":"Go语言101","Students":[{"Id":1,"Gender":"男","Name":"学生1"},{"Id":2,"Gender":"男","Name":"学生2"},{"Id":3,"Gender":"男","Name":"学生3"},{"Id":4,"Gender":"男","Name":"学生4"},{"Id":5,"Gender":"男","Name":"学生5"},{"Id":6,"Gender":"男","Name":"学生6"},{"Id":7,"Gender":"男","Name":"学生7"},{"Id":8,"Gender":"男","Name":"学生8"},{"Id":9,"Gender":"男","Name":"学生9"},{"Id":10,"Gender":"男","Name":"学生10"}]}`
	var c1 = &Class{} // 指针变量
	err1 := json.Unmarshal([]byte(str1), c1)
	if err1!= nil {
		fmt.Println(err1)
		return
	}else{
		fmt.Println(c1)
	}
}